package AuthInAction;

use strict;
use CGI;

use Athena::WebAPI::Response;
use Athena::Connection;
use Athena::ErrorView;
# this is the default view
use Athena::ChooseMethodAction;
use Athena::ChooseLbAction;
use Athena::AuthInAction;
use Athena::ViewPhysAction;
use Athena::ViewFarmAction;
use Athena::ViewEngineAction;
use Athena::UpdatePhysAction;
use Athena::UpdateFarmAction;
use Athena::BalanceAction;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $rResponse = undef;
  my $cConn = undef;

  my %hDefaultTableStyle = (
			   -align=>'center',
			   -border=>1,
			   -cellpadding=>3,
			   -bgcolor=>"#cccccc"
			  );

  my %hDefaultBodyStyle = (
			   -text=> "#000000",
			   -link=> "#700000",
			   -vlink=>"#700000",
			   -bgcolor=> '#ffffff'
			  );
  my $stTableStyle = \%hDefaultTableStyle;
  my $stBodyStyle = \%hDefaultBodyStyle;

  ## insert auth tests here ##
  
  if (($rRequest->cookie('AthenaEngineHost')
       && ($rRequest->cookie('AthenaEnginePort')))) {
    $cConn = Connection->new('host'=>$rRequest->cookie('AthenaEngineHost'),
			     'port'=>$rRequest->cookie('AthenaEnginePort'));
    
    if (not $cConn->connect()) {
      my $stErrMsg = "Athena Connection Error: [".$!."]";
      my $stErrBody =
	"<br><font color=\"#800000\">"
	  . "Please check that athena demon is running on "
	    ."<br>Host: ". b($cConn->getHost()) 
	      . " Port: ". b($cConn->getPort())
		."</font>";
      my $rView = ErrorView->new('err_msg'=>$stErrMsg,
				 'err_body'=>$stErrBody,
				 'body_style'=>$stBodyStyle, 
				 'table_style'=>$stTableStyle,
				);
      $rResponse = Response->new($rView);
      $cConn = undef;
      return $rResponse;
    }
  }
  elsif ($rRequest->cookie('AthenaEngineUrl')) {
    $cConn = Connection->new('url'=>$rRequest->cookie('AthenaEngineUrl'));
  }

  my $stAction;
  if ($cConn) {
    $stAction = $rRequest->action();
    #if (not exists($Athena::{$stAction.'::'})) {
    eval "require Athena::$stAction;";
    if ($@) {
      $stAction = $rRequest->action('ViewPhysAction');
    }
    $rResponse = $stAction->execute($rRequest, $cConn, 
				    'body_style'=>$stBodyStyle, 
				    'table_style'=>$stTableStyle,
				   );
    $cConn->disconnect();
  }
  else {
    $stAction = $rRequest->action('ChooseMethodAction');
    $rResponse = $stAction->execute($rRequest, $cConn,
				    'body_style'=>$stBodyStyle,
				    'table_style'=>$stTableStyle,
				   );
  }
  
  return $rResponse;
}

1;
